//
//  ContactDetailViewController.m
//  ExpressData
//
//  Created by Sun Thurein Aung on 5/01/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ContactDetailViewController.h"


@implementation ContactDetailViewController

@synthesize keyList;
@synthesize addressDetail;
UILabel *subtitleLabel;

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSString *) tableView:(UITableView *)table titleForHeaderInSection:(NSInteger)section {
	return [addressDetail valueForKey:@"Branch Name"];
}

- (NSString *) tableView:(UITableView *)table titleForFooterInSection:(NSInteger)section {
	return @"Click on the phone, fax or email for more action";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [keyList count]-3;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
	subtitleLabel = (UILabel*)[cell viewWithTag:1];
	UIActionSheet *actionSheet;
	
	if ([self isEmail:subtitleLabel.text]){
		actionSheet = [[UIActionSheet alloc] initWithTitle:@"Available Actions"
												  delegate:self
										 cancelButtonTitle:@"Cancel"
									destructiveButtonTitle:nil
										 otherButtonTitles:@"Send Email", @"Add to Contacts",@"Copy to clipboard",nil];
	}else if ([self isPhoneNumber:subtitleLabel.text]){
		actionSheet = [[UIActionSheet alloc] initWithTitle:@"Available Actions"
												  delegate:self
										 cancelButtonTitle:@"Cancel"
									destructiveButtonTitle:nil
										 otherButtonTitles:@"Call", @"Add to Contacts",@"Copy to clipboard",nil];
	}
	else {
		actionSheet = [[UIActionSheet alloc] initWithTitle:@"Available Actions"
												  delegate:self
										 cancelButtonTitle:@"Cancel"
									destructiveButtonTitle:nil
										 otherButtonTitles:@"Copy to clipboard", nil];
	}

	[actionSheet showInView:self.view];
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	
}
-(BOOL) isEmail : (NSString *)emailAddress{
	
    NSString *emailRegEx =
    @"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
    @"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
    @"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
    @"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
    @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
    @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
    @"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
    
    NSPredicate *regExPredicate =
    [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
    return [regExPredicate evaluateWithObject:emailAddress];
	
}

-(BOOL) isPhoneNumber : (NSString *)phoneNumber{

	NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:nil];
	NSArray* matches = [detector matchesInString:phoneNumber options:0 range:NSMakeRange(0, [phoneNumber length])];
	for (id match in matches) {
		return TRUE;
	}
    return FALSE;

}

-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
	NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
	
	if ([buttonTitle isEqualToString:@"Call"]) {
		NSString *ph_no = [NSString stringWithFormat:@"tel://%@", subtitleLabel.text];
		ph_no = [ph_no stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:ph_no]];
		[ph_no release];
	}
	
	if ([buttonTitle isEqualToString:@"Send Email"]) {
		NSString *email = [NSString stringWithFormat:@"mailto:%@?subject=Express Data Enquiry", subtitleLabel.text];
		email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
		[email release];
		
	}
	if ([buttonTitle isEqualToString:@"Copy to clipboard"]) {
		UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
		[pasteBoard setValue:subtitleLabel.text forPasteboardType:@"public.utf8-plain-text"];
		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Copied to clipboard"
														   message :[NSString stringWithFormat:@"%@  copied to clipboard.", subtitleLabel.text]
														  delegate :nil
												  cancelButtonTitle:@"Ok"
												  otherButtonTitles:nil];
			[alertView show];
			[alertView release];
	}
	if ([buttonTitle isEqualToString:@"Add to Contacts"]) {
		ABAddressBookRef addressBook = ABAddressBookCreate();
		ABRecordRef company = ABPersonCreate();
//		CFErrorRef  error = NULL; 
		
		
		ABRecordSetValue(company, kABPersonOrganizationProperty, @"Express Data", nil);
		
		// Adding the Phone details a person may have multiple phone numbers
		ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);

		ABMultiValueAddValueAndLabel(multiPhone, @"0430195407", CFSTR("Work"), NULL);
		ABMultiValueAddValueAndLabel(multiPhone, @"0430195407", CFSTR("Customer Service"), NULL);
		ABMultiValueAddValueAndLabel(multiPhone, @"0430195497", CFSTR("Fax"), NULL);
		ABRecordSetValue(company, kABPersonPhoneProperty, multiPhone, nil);
		if (multiPhone) {
			CFRelease(multiPhone);
		}
		
		UIImage *image = [UIImage imageNamed:@"ED-logo-small.png"];
		NSData *dataRef = UIImagePNGRepresentation(image); 
		CFDataRef cfdata = CFDataCreate(NULL, [dataRef bytes], [dataRef length]);
		CFErrorRef error;
		
		ABPersonRemoveImageData(company, &error); // <-- clean any image first from ref
		ABAddressBookSave(addressBook, &error);
		
		//int ret = ABPersonSetImageData(company, cfdata, &error);
		ABPersonSetImageData(company, cfdata, &error);
		//if (ret) {
		//	ret = ABAddressBookSave(addressBook, &error);
		//} else {
		//	NSLog(@"Could not write the image to the person");
		//}
	
		CFRelease(cfdata);
		
		
		ABMutableMultiValueRef urlMultiValue = 
		ABMultiValueCreateMutable(kABStringPropertyType);
		ABMultiValueAddValueAndLabel(urlMultiValue, @"https://www.expressdata.com.au",
									 kABPersonHomePageLabel, NULL);
		
		ABRecordSetValue(company, kABPersonURLProperty, urlMultiValue, &error);
		CFRelease(urlMultiValue);
		
		ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
        ABMultiValueAddValueAndLabel(multiEmail, @"saung@expressdata.com", CFSTR("Work Email"), NULL);
        ABRecordSetValue(company, kABPersonEmailProperty, multiEmail, &error);
        CFRelease(multiEmail);
		
		
		ABAddressBookAddRecord(addressBook, company, nil);
		ABAddressBookSave(addressBook, nil);
		
		CFRelease(company);		
		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Contact Detail Added"
														   message :[NSString stringWithFormat:@"Contact Details are added to your address book.", subtitleLabel.text]
														  delegate :nil
												  cancelButtonTitle:@"Ok"
												  otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}
	


}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
		CGSize subtitleLabelSize = [[addressDetail valueForKey:[keyList objectAtIndex:indexPath.row +1]] sizeWithFont:[UIFont fontWithName:@"HelveticaNeue" size:14] constrainedToSize: CGSizeMake(150.f, 50.f) lineBreakMode: UILineBreakModeWordWrap];
	return subtitleLabelSize.height + 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSString *identifier = @"ContactDetail";
	UITableViewCell *detailCell = [tableView
								   dequeueReusableCellWithIdentifier:identifier];
	if (detailCell == nil) {
		detailCell = [[[UITableViewCell alloc]
					   initWithStyle: UITableViewCellStyleDefault
					   reuseIdentifier:identifier] autorelease];
	}
	
	detailCell.textLabel.text = [keyList objectAtIndex:indexPath.row + 1];
	detailCell.textLabel.font = [UIFont boldSystemFontOfSize:12];
	
	

	
	UILabel *subtitleLabel = [[UILabel alloc] init];
	subtitleLabel.frame = CGRectMake( 140.0, 11.0, 150.0, 30);
	subtitleLabel.text = [addressDetail valueForKey:[keyList objectAtIndex:indexPath.row +1]];
	subtitleLabel.textAlignment = UITextAlignmentLeft;
	subtitleLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:14];
	

	subtitleLabel.shadowColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.7];
	subtitleLabel.shadowOffset = CGSizeMake(0, -1.0);
	subtitleLabel.backgroundColor = [UIColor clearColor];
	subtitleLabel.lineBreakMode = UILineBreakModeWordWrap;
	subtitleLabel.numberOfLines = 5;
	subtitleLabel.tag = 1;
	CGSize subtitleLabelSize = [[addressDetail valueForKey:[keyList objectAtIndex:indexPath.row +1]] sizeWithFont: subtitleLabel.font constrainedToSize: CGSizeMake(150.f, 50.f) lineBreakMode: subtitleLabel.lineBreakMode];
	subtitleLabel.frame = CGRectMake(subtitleLabel.frame.origin.x, subtitleLabel.frame.origin.y, subtitleLabelSize.width, subtitleLabelSize.height);
	
	
	[detailCell.contentView addSubview:subtitleLabel];
	//	[detailCell.contentView
	//	 addSubview:[preferenceObjects objectAtIndex:indexPath.row]];
	return detailCell;
}



// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
	self.title = @"Contact Detail";
	self.view.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"background1.png"]];
	
	
    [super viewDidLoad];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
